package com.shenyue.nbtownlet.activity;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.SearchView;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.shenyue.nbtownlet.R;
import com.shenyue.nbtownlet.adapter.OfficeCheckListViewAdapter;
import com.shenyue.nbtownlet.base.BaseActivity;
import com.shenyue.nbtownlet.databinding.ActivityOfficeCheckBinding;
import com.shenyue.nbtownlet.event.BaseListener;
import com.shenyue.nbtownlet.model.AppLoginModel;
import com.shenyue.nbtownlet.model.AppTaskModel;
import com.shenyue.nbtownlet.model.DefaultModel;
import com.shenyue.nbtownlet.util.NetWorkUtils;
import com.shenyue.nbtownlet.util.StringUtil;

/**
 * 发文管理
 */
public class OfficeCheckActivity extends BaseActivity implements OfficeCheckListViewAdapter.OfficeCheckListItemClickListener {
    private ActivityOfficeCheckBinding binding;
    private Context mContext;
    private OfficeCheckListViewAdapter listViewAdapter;
    private int pageNo = 1, pageSize = 10;
    private Handler mHandler = new Handler();
    private MenuItem searchMenu;
    private SearchView searchView;
    private String status = "0";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = DataBindingUtil.setContentView(this, R.layout.activity_office_check);
        setActionBar(true, getString(R.string.tv_office_check));
        mContext = this;

        listViewAdapter = new OfficeCheckListViewAdapter(mContext);
        binding.listView.setAdapter(listViewAdapter);
        listViewAdapter.setOnItemClickListener(this);

        binding.ptrClassicFrameLayout.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                if (!NetWorkUtils.isNetworkConnected(mContext)) {
                    binding.ptrClassicFrameLayout.refreshComplete();
                    showMsg(getString(R.string.no_network));
                    return;
                }
                query();
            }
        });

        binding.ptrClassicFrameLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
                if (!NetWorkUtils.isNetworkConnected(mContext)) {
                    binding.ptrClassicFrameLayout.loadMoreComplete(false);
                    showMsg(getString(R.string.no_network));
                    return;
                }
                queryMore();
            }
        });
        binding.ptrClassicFrameLayout.disableWhenHorizontalMove(true);

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                binding.ptrClassicFrameLayout.autoRefresh();
            }
        }, 32);
    }

    private void query() {
        listViewAdapter.clear();
        pageNo = 1;
        JSONObject param = new JSONObject();
        param.put("status", StringUtil.getValue(status));
        param.put("title", searchView == null ? "" : searchView.getQuery().toString());
        param.put("type", "1");
        param.put("userID", AppLoginModel.getIdentityId(mContext));
        param.put("pagenumber", pageNo);
        param.put("pagesize", pageSize);
        AppTaskModel.WaitList(mContext, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                binding.ptrClassicFrameLayout.refreshComplete();
                JSONObject data = JSON.parseObject(val);
                long count = data.getLong("count");
                JSONArray array = data.getJSONArray("data");
                binding.ptrClassicFrameLayout.setLoadMoreEnable(!(count < pageSize));
                listViewAdapter.addItems(array);
            }

            @Override
            public void error(String error, String action) {
                binding.ptrClassicFrameLayout.refreshComplete();
                showMsg(error);
            }
        });
    }

    private void queryMore() {
        pageNo += 1;
        JSONObject param = new JSONObject();
        param.put("status", StringUtil.getValue(status));
        param.put("title", searchView == null ? "" : searchView.getQuery().toString());
        param.put("type", "1");
        param.put("userID", AppLoginModel.getIdentityId(mContext));
        param.put("pagenumber", pageNo);
        param.put("pagesize", pageSize);
        AppTaskModel.WaitList(mContext, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                JSONObject data = JSON.parseObject(val);
                long count = data.getLong("count");
                JSONArray array = data.getJSONArray("data");
                binding.ptrClassicFrameLayout.loadMoreComplete(!(count < (pageNo * pageSize)));
                listViewAdapter.addItems(array);
            }

            @Override
            public void error(String error, String action) {
                binding.ptrClassicFrameLayout.loadMoreComplete(false);
                showMsg(error);
            }
        });
    }

    private void setSearchView() {
        if (this.searchView != null) {
            EditText searchPlate = (EditText) this.searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
            if (searchPlate == null)
                return;
            searchPlate.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        binding.ptrClassicFrameLayout.autoRefresh();
                    }
                    return false;
                }
            });
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.action_menu, menu);
        searchMenu = menu.findItem(R.id.action_search);
        searchView = (SearchView) searchMenu.getActionView();
        searchView.setQueryHint("请输入名称检索");
        setSearchView();
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        hideSearchView();
        switch (item.getItemId()) {
            case R.id.btn_001:
                status = "0";
                binding.ptrClassicFrameLayout.autoRefresh();
                break;
            case R.id.btn_002:
                status = "1";
                binding.ptrClassicFrameLayout.autoRefresh();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void hideSearchView() {
        if (this.searchMenu != null)
            this.searchMenu.collapseActionView();
    }

    @Override
    public void onItemClick(int position) {
        if (!NetWorkUtils.isNetworkConnected(mContext)) {
            showMsg(getString(R.string.no_network));
            return;
        }
        JSONObject item = (JSONObject) listViewAdapter.getItem(position);
        JSONObject flow = item.getJSONObject("flow");
        String InstanceID = StringUtil.dTs(flow.getString("InstanceID"));
        Bundle bundle = new Bundle();
        bundle.putString(DefaultModel.PAGE_DATA_ID, InstanceID);
        toActivity(OfficeCheckDetailActivity.class, bundle);
    }
}
